<?php

namespace App\Services;

use App\Models\WeChatKeyWord;
use App\Models\WeChatRule;

class WeChatService
{
    public function save($type = null,string $module=null, array $options = [])
    {

        $rule = json_decode(request()->input('wechat.rule'), true);
//空标题

        //同一个站点，同模块，同微信，
        if ($rule['title']) {
            $wechatRule = WeChatRule::updateOrCreate(
                [
                    'id' => $rule['id'] ?? 0
                ],
                ['site_id' => site()['id'],
                    'module_id' => module()['id'],
                    'wechat_id' => $rule['wechat_id'],
                    'type' => $type,
                    'title' => $rule['title'],
                    'module' => $module,
                    'options' => $options
                ]
            );
            $this->saveKeyWord($wechatRule);
            return $wechatRule;
        }
    }

    public function saveKeyWord(WeChatRule $weChatRule)
    {
        //textarea v-html 方式提交的string数据，通过json_decode进行解析。

        $keywords = json_decode(request()->input('wechat.keywords'), true);
//删除规则关联的所有关键字，再增加提交的ID，实现同步更新效果。id也需要跟着填充，否则会不断产生新的id
        $weChatRule->keywords()->delete();

        foreach ($keywords as $keyword) {
            $id = $keyword['id'] ?? 0;
//同关键词，同模块，同微信  ,同站点，至出现一次word
            if (!$this->checkKeywordIsExists($keyword)) {
                WeChatKeyWord::updateOrCreate(
                    [
                        'id' => $id
                    ], [
                        'site_id' => site()['id'],
                        'module_id' => module()['id'],
                        'rule_id' => $weChatRule['id'],
                        'wechat_id' => $weChatRule['wechat_id'],
                    ] + $keyword);

            }

        }

    }

    public function checkKeywordIsExists($keyword)
    {
        //没有检测模块，是因为要一个微信可以对应多个模块

        return $has = WeChatKeyWord::where('site_id', site()['id'])
            ->where('word', trim($keyword['word']))
            ->whereNotIn('id', [$keyword['id'] ?? 0])
            ->exists();
    }
}







